var ProjectAdd = function () {
	var handleValidation = function() {
		var fileList = new Array();
		$("#zyupload").zyUpload({
			width            :   "650px",                 // 宽度
			height           :   "150px",                 // 宽度
			itemWidth        :   "140px",                 // 文件项的宽度
			itemHeight       :   "115px",                 // 文件项的高度
			url              :   "/upload/UploadAction",  // 上传文件的路径
			fileType         :   ["docx","doc","pdf","jpg","jpeg","png","txt"],// 上传文件的类型
			fileSize         :   51200000,                // 上传文件的大小
			multiple         :   false,                    // 是否可以多个文件上传
			dragDrop         :   false,                   // 是否可以拖动上传文件
			tailor           :   false,                   // 是否可以裁剪图片
			del              :   true,                    // 是否可以删除文件
			finishDel        :   false,  				  // 是否在上传文件完成后删除预览
			/* 外部获得的回调接口 */
			onSelect: function(selectFiles, allFiles){    // 选择文件的回调方法  selectFile:当前选中的文件  allFiles:还没上传的全部文件
				fileList.push(selectFiles[0]);
				console.info("fileList",fileList);
			},
			onDelete: function(file, files){              // 删除一个文件的回调方法 file:当前删除的文件  files:删除之后的文件
				console.info("当前删除了此文件：");
				console.info(file.name);
				for(var i=1 ;i<fileList.length;i++){
					if(fileList[i].name == file.name){
						fileList.splice(i,1);
					}
				}
				console.info("fileListd",fileList);
			},
			onSuccess: function(file, response){          // 文件上传成功的回调方法
				console.info("此文件上传成功：");
				console.info(file.name);
				console.info("此文件上传到服务器地址：");
				console.info(response);
				$("#uploadInf").append("<p>上传成功，文件地址是：" + response + "</p>");
			},
			onFailure: function(file, response){          // 文件上传失败的回调方法
				console.info("此文件上传失败：");
				console.info(file.name);
			},
			onComplete: function(response){           	  // 上传完成的回调方法
				console.info("文件上传完成");
				console.info(response);
			}
		});
			$('#type').change(function(){ 
				var selected = $(this).children('option:selected').val(); 
				var guaranteeTypeDiv = $('#guaranteeTypeDiv');
				var guaranteeAssessDiv = $('#guaranteeAssessDiv');
				if (2 == selected){
					guaranteeTypeDiv.css('display','none');
					guaranteeAssessDiv.css('display','none');
				} else {
					guaranteeTypeDiv.css('display','block');
					guaranteeAssessDiv.css('display','block');
				}
			}) 
			$('#guaranteeType').change(function(){ 
				var selected = $(this).children('option:selected').val(); 
				var obj = $('#guaranteeLabel');
				var guaranteeAssessDiv = $('#guaranteeAssessDiv');
				var guaranteeAssessLabel = $('#guaranteeAssessLabel');
				switch (selected) {
                case ("1"):
                		obj.html('<font color="red">*&nbsp;&nbsp;</font>保证人:');
						guaranteeAssessDiv.css('display','none');
                    break;
                case ("2"):
	                	obj.html('<font color="red">*&nbsp;&nbsp;</font>抵押人:');
                		guaranteeAssessDiv.css('display','block');
                		guaranteeAssessLabel.html('<font color="red">*&nbsp;&nbsp;</font>抵押物状况/评估:')
                    break;
                case ("3"):
	                	obj.html('<font color="red">*&nbsp;&nbsp;</font>质押人:');
                		guaranteeAssessDiv.css('display','block');
                		guaranteeAssessLabel.html('<font color="red">*&nbsp;&nbsp;</font>质押物状况/评估:')
                    break;
                case ("4"):
                		obj.html('<font color="red">*&nbsp;&nbsp;</font>留置人:');
		                guaranteeAssessDiv.css('display','block');
		        		guaranteeAssessLabel.html('<font color="red">*&nbsp;&nbsp;</font>备注:')
                      break;
                case ("5"):
                		obj.html('<font color="red">*&nbsp;&nbsp;</font>缴款人:');
		                guaranteeAssessDiv.css('display','block');
		        		guaranteeAssessLabel.html('<font color="red">*&nbsp;&nbsp;</font>备注:')
                      break;
                default:
				}
			}) 
		
            var formAdd = $('#addForm');
            jQuery.validator.addMethod("isCorrectNumber", function(value, element) {
            	var length = value.length;
            	var number = /^([1-9]\d*(.\d{2})?)$/;
            	return this.optional(element) || number.test(value);
            	}, "请输入正确的金额(正整数)");
            var validator = formAdd.validate({
                focusInvalid: true,
                rules: {
                	name: {
                        required: true,
                        remote:{
                        	url: ctx + "/project/check",
                            type: "post",
                            dataType: "json",
                            data: {type : 1}
                        },
                        rangelength:[1,64],
                    },
                    code:{
                    	required: true,
                    	remote:{
                        	url: ctx + "/project/check",
                            type: "post",
                            dataType: "json",
                            data: {type : 2}
                        },
                        rangelength:[1,32],
                    },
                    type:{
                    	required: true,
                    },
                    enterpriseId:{
                    	required: true,
                    },
                    guaranteeType:{
                    	required: true,
                    },
                    guaranteeEnterpriseId:{
                    	required: true,
                    },
                    guaranteeAssess:{
                    	required: true,
                    },
                    amount:{
                    	required: true,
                    	isCorrectNumber:true,
                    },
                    lawEmployeeId:{
                    	required: true,
                    },
                    summary:{
                    	required: true
                    }
                },
                messages:{
                	name: {
                        required: "项目名称不能为空",
                        remote:"项目名称已被使用",
                    },
                    code: {
                        required: "项目编号不能为空",
                        remote:"项目编号已被使用",
                    },
                	guaranteeAssess:{
	                    required:"抵押物状况/评估不能为空"
	                  },
                },
                success: function (label, element) {
                    var icon = $(element).parent('.input-icon').children('i');
                    $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                    icon.removeClass("fa-warning").addClass("fa-check");
                },

                submitHandler: function (form) {
                	$('#submit_manager').attr('disabled',true);
                	validateContent();
                	validateContent1();
                    var content = $($('.note-editable')[0]).code();
                    if("" == content.trim() || "<p><br></p>" == content.trim()){
                    	return;
                    }
                    var plan = $($('.note-editable')[1]).code();
                    if("" == plan.trim() || "<p><br></p>" == plan.trim()){
                    	return;
                    }
                    var fd = new FormData();
                    for(var i=0;i<fileList.length;i++){
                    	fd.append("fileList", fileList[i]);
                    }
                    fd.append("amount",$('input[name="amount"]').val());
                    fd.append("lawEmployeeId",$('select[name="lawEmployeeId"]').val());
                    fd.append("guaranteeAssess",$('textarea[name="guaranteeAssess"]').val());
                    fd.append("guaranteeType",$('select[name="guaranteeType"]').val());
                    fd.append("guaranteeEnterpriseId",$('select[name="guaranteeEnterpriseId"]').val());
                    fd.append("type",$('select[name="type"]').val());
                    fd.append("enterpriseId",$('select[name="enterpriseId"]').val());
                    fd.append("name",$('input[name="name"]').val());
                    fd.append("code",$('input[name="code"]').val());
                    fd.append("introduction",content);
                    fd.append("plan",plan);
                    
                    var xhr = new XMLHttpRequest();
                    xhr.addEventListener("load", uploadComplete, false);
                    xhr.addEventListener("error", uploadFailed, false);
                    xhr.open("POST",ctx + "/project/doAdd");
                    xhr.send(fd);
                    
                    function uploadComplete(evt) {
                        var msg = JSON.parse(evt.target.responseText);
                        if(0 == msg.code){
                    		bootbox.alert(msg.message);
                    		$('#submit_manager').removeAttr("disabled");
                    		return;
                    	}
                    	bootbox.alert({  
                            buttons: {  
                               ok: {  
                                    label: '确认',  
                                    className: 'btn-primary'  
                                }  
                            },  
                            message: '新增项目成功！',  
                            callback: function() {  
                            	$('#submit_manager').removeAttr("disabled");
                            	//重定向到未入库项目页面
                            	window.location.href = ctx +"/project/nonInStoreList";
                            },  
                            title: "提示信息",  
                        }); 
                    	$('#submit_manager').removeAttr("disabled");
                      }

                      function uploadFailed(evt) {
                        alert("There was an error attempting to upload the file.");
                      }
                }
            });
            $('button[name="addEnterprise"]').click(function(){
            	window.location.href=ctx+'/enterprise/add';
            });
            
            var validateContent = function(){
            	var c = $($('.note-editable')[0]).html().toString();
            	if("" == c.trim() || "<p><br></p>" == c.trim()){
            		$($('.note-editor')[0]).removeClass("content-control has-success").addClass("content-control error");
	            	if($('#content-label').hasClass("content-success")){
	            		$('#content-label').removeClass("content-success");
	            	}
	            	$("#contents-error").html('内容不能为空'); 
	            	$("#contents-error").css('display','inline'); 
	            }else{
	            	$($('.note-editor')[0]).removeClass("content-control error").addClass("content-control has-success");
	            	$('#content-label').addClass("content-success");
	            	$("#contents-error").css('display','none'); 
	            }
            };
            var validateContent1 = function(){
            	var c = $($('.note-editable')[1]).html().toString();
            	if("" == c.trim() || "<p><br></p>" == c.trim()){
	            	$($('.note-editor')[1]).removeClass("content-control has-success").addClass("content-control error");
	            	if($('#content-label1').hasClass("content-success")){
	            		$('#content-label1').removeClass("content-success");
	            	}
	            	$("#contents-error1").html('内容不能为空'); 
	            	$("#contents-error1").css('display','inline'); 
	            }else{
	            	$($('.note-editor')[1]).removeClass("content-control error").addClass("content-control has-success");
	            	$('#content-label1').addClass("content-success");
	            	$("#contents-error1").css('display','none'); 
	            }
            };
            $($('.summernote')[0]).summernote({
            	height: 500, 
            	toolbar: [  
            	          ['style', ['style']],
            	          ['style', ['bold', 'italic', 'underline', 'clear']],  
            	          ['fontsize', ['fontsize']],  
            	          ['fontname',['fontname']],
            	          ['color', ['color']],  
            	          ['para', ['ul', 'ol', 'paragraph']],  
            	          ['height', ['height']],  
            	          ['table',['table']],
            	          ['insert', ['picture','link']] ,
            	          ['help',['help']]
            	        ], 
            	onImageUpload: function(files, editor, $editable) {
                     sendFile(files,editor,$editable);
                    },
                onblur: function(e) {
                	validateContent();
                },
                onfocus:function(e){
                	validateContent();
                },
                onChange: function(contents, $editable) {
                	validateContent();
                },
                bFullscreen:false,
                
            });
            $($('.summernote')[1]).summernote({
            	height: 500, 
            	toolbar: [  
            	          ['style', ['style']],
            	          ['style', ['bold', 'italic', 'underline', 'clear']],  
            	          ['fontsize', ['fontsize']],  
            	          ['fontname',['fontname']],
            	          ['color', ['color']],  
            	          ['para', ['ul', 'ol', 'paragraph']],  
            	          ['height', ['height']],  
            	          ['table',['table']],
            	          ['insert', ['picture','link']] ,
            	          ['help',['help']]
            	        ], 
            	onImageUpload: function(files, editor, $editable) {
                     sendFile(files,editor,$editable);
                    },
                onblur: function(e) {
                	validateContent1();
                },
                onfocus:function(e){
                	validateContent1();
                },
                onChange: function(contents, $editable) {
                	validateContent1();
                },
                bFullscreen:false,
                
            });
            function sendFile(file, editor, $editable) {
            	for(var i = 0;i < file.length;i++){
            		data = new FormData();
                    data.append("file", file[i]);
                    url = ctx+"/project/imgUploads";
                    $.ajax({
                        data: data,
                        type: "POST",
                        url: url,
                        cache: false,
                        contentType: false,
                        processData: false,
                        success: function (msg) {
                        	if(1 == msg.code){
                        		editor.insertImage($editable, imagePrefix+msg.data);
                        	}
                        	else{
                        		bootbox.alert(msg.message);
                        	}
                        }
                 	});
            	}
       		};
    }

    return {
        init: function () {
            handleValidation();
        }
    };
}();
